package com.example.demo.project2.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.demo.project2.util.ExceptionUtil;
import org.springframework.stereotype.Service;

@Service
public class TestService {

    // 原函数
    @SentinelResource(value = "fusingTest", blockHandler = "exceptionHandler", fallback = "testfallbackHandler")
    public String fusingTest(long s) throws InterruptedException {
        if (s == 1){
            Thread.sleep(1000);
        }else if (s == 2){
            int i = 1/0;
        }
        return String.format("调用成功: %d",s);
    }

    // Fallback 函数，函数签名与原函数一致或加一个 Throwable 类型的参数.
    public String testfallbackHandler(long s) {
        return String.format("系统报错 %d", s);
    }

    // Block 异常处理函数，参数最后多一个 BlockException，其余与原函数一致.
    public String exceptionHandler(long s, BlockException ex) {
        ex.printStackTrace();
        return "系统熔断222：" + s;
    }

    // 这里单独演示 blockHandlerClass 的配置.
    // 对应的 `handleException` 函数需要位于 `ExceptionUtil` 类中，并且必须为 public static 函数.
    @SentinelResource(value = "fusingTest2", blockHandler = "handleException", blockHandlerClass = {ExceptionUtil.class})
    public String fusingTest2(long s) throws InterruptedException {
        if (s == 1){
            Thread.sleep(1000);
        }
        return "test";
    }
}
